package com.example.neuronview

import android.content.Context
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlin.coroutines.resumeWithException

// 自定义包装类，用于保存 PorterDuffColorFilter 的颜色和混合模式
class CustomPorterDuffColorFilter(
    val color: Int,  // 存储颜色值（公开可访问）
    val mode: PorterDuff.Mode,  // 存储混合模式（公开可访问）
    colorFilter: PorterDuffColorFilter = PorterDuffColorFilter(color, mode)
) : PorterDuffColorFilter(color,mode)  {
    // 直接复用原始 PorterDuffColorFilter 的功能，同时暴露 color 和 mode
}
class NeuronAdapter(val context: Context, var neurons:MutableList<Neuron>): BaseAdapter(){
    private lateinit var checkbox:  CheckBox
    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    fun updateData(isChecked: Boolean,item:Sample){
        if (isChecked) {
//            showToast("加载${item.sampleid}")
            val httpData = HttpData(context)
            httpData.neuronList = neurons
            httpData.fetchNeuronData(this, item)
        }else{
            neurons.forEach { neuron ->
                if (neuron.isSelected && neuron.sampleid==item.sampleid) {
                    neuron.isSelected = false
                    onCheckBoxStateChanged?.invoke(0,false,neuron,Color.argb(neuron.color.a.toInt(),neuron.color.r.toInt(),neuron.color.g.toInt(),neuron.color.b.toInt()))
                }
            }
            neurons.removeIf {  it.sampleid==item.sampleid }
            println(neurons)
            notifyDataSetChanged()
        }
    }
    private suspend fun fetchNeuronFileSuspend(neuron: Neuron): String {
        return suspendCancellableCoroutine { continuation ->
            val httpData = HttpData(context)
            httpData.fetchNeuronFile(
                neuron.sampleid,
                neuron.name,
                onSuccess = { filePath ->
                    continuation.resume(filePath) {}
                },
                onFailure = { errorMsg ->
                    continuation.resumeWithException(Exception(errorMsg))
                }
            )
        }
    }
    private fun processNeuronsWithCoroutine(neurons: List<Neuron>, isChecked: Boolean) {
        CoroutineScope(Dispatchers.IO).launch {
            for (neuron in neurons) {
                if (isChecked) {
                    try {
                        // 串行执行：一个请求完成再处理下一个
                        val filePath = fetchNeuronFileSuspend(neuron)
                        neuron.filePath = filePath
                        if (neuron.isSelected != isChecked) {
                            neuron.isSelected = isChecked
                            // 切换到主线程更新UI和回调
                            withContext(Dispatchers.Main) {
                                onCheckBoxStateChanged?.invoke(
                                    0,
                                    isChecked,
                                    neuron,
                                    Color.argb(
                                        neuron.color.a.toInt(),
                                        neuron.color.r.toInt(),
                                        neuron.color.g.toInt(),
                                        neuron.color.b.toInt()
                                    )
                                )
                                notifyDataSetChanged()

                            }
                        }
                    } catch (e: Exception) {
                        withContext(Dispatchers.Main) {
                            showToast("处理 ${neuron.name} 失败：${e.message}")
                        }
                    }
                } else {
                    // 未选中状态，直接更新
                    neuron.isSelected = isChecked
                    withContext(Dispatchers.Main) {
                        onCheckBoxStateChanged?.invoke(
                            0,
                            isChecked,
                            neuron,
                            Color.argb(
                                neuron.color.a.toInt(),
                                neuron.color.r.toInt(),
                                neuron.color.g.toInt(),
                                neuron.color.b.toInt()
                            )
                        )
                    }
                }
            }
            // 所有处理完成后，主线程刷新列表
            withContext(Dispatchers.Main) {
                notifyDataSetChanged()
            }
        }
    }
    fun selectAllCoroutine(isChecked: Boolean){
        if(isChecked){
            processNeuronsWithCoroutine(neurons, isChecked)
        }else {
            // 未选中状态仍可批量处理（无需网络请求，可直接循环）
            neurons.forEach { neuron ->
                neuron.isSelected = isChecked
                onCheckBoxStateChanged?.invoke(0,isChecked,neuron,Color.argb(neuron.color.a.toInt(),neuron.color.r.toInt(),neuron.color.g.toInt(),neuron.color.b.toInt()))

            }
            notifyDataSetChanged()
        }
    }
    fun selectAll(isChecked: Boolean){

        neurons.forEach { neuron ->
            if (isChecked)
            {
                val httpData = HttpData(context)
                httpData.fetchNeuronFile(neuron.sampleid,neuron.name, onSuccess = {filePath->
                    neuron.filePath=filePath
                    if (neuron.isSelected !=isChecked) {
                        neuron.isSelected = isChecked
                        onCheckBoxStateChanged?.invoke(0,isChecked,neuron,Color.argb(neuron.color.a.toInt(),neuron.color.r.toInt(),neuron.color.g.toInt(),neuron.color.b.toInt()))
                    }

                }, onFailure = {errorMsg->
                    showToast(errorMsg)
                })
            }else {
                neuron.isSelected = isChecked

                onCheckBoxStateChanged?.invoke(0,isChecked,neuron,Color.argb(neuron.color.a.toInt(),neuron.color.r.toInt(),neuron.color.g.toInt(),neuron.color.b.toInt()))
                notifyDataSetChanged()

            }
        }

    }

    var onCheckBoxStateChanged:((position:Int, isChecked: Boolean, item:Neuron, color:Int)->Unit)?=null

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
        val view: View
        val viewHolder: ViewHolder

        if (convertView == null) {
            // 新建视图并创建ViewHolder
            view = LayoutInflater.from(context).inflate(R.layout.neuronitem, parent, false)
            viewHolder = ViewHolder()
            viewHolder.checkBox = view.findViewById(R.id.ckNeuron)

            view.tag = viewHolder // 将ViewHolder存储在View中
        } else {
            // 复用已有视图和ViewHolder
            view = convertView
            viewHolder = view.tag as ViewHolder
        }
        // 获取当前位置的数据
        val item = neurons[position]
        // 取消之前的监听器，避免复用导致的问题
        viewHolder.checkBox.setOnCheckedChangeListener(null)
        // 根据数据设置复选框状态
        viewHolder.checkBox.isChecked = item.isSelected

        // 重新设置监听器
        viewHolder.checkBox.setOnCheckedChangeListener { _, isChecked ->
            // 更新数据模型中的状态
            item.isSelected = isChecked
            val currentColor = view.findViewById<View>(R.id.colorNeuron).background.colorFilter as CustomPorterDuffColorFilter
            currentColor.color
            // 触发回调
            if (isChecked){
//                var msg = "被选中$sampleid $name";
                val httpData = HttpData(context)
                httpData.fetchNeuronFile(item.sampleid,item.name, onSuccess = {filePath->
                    val neuron = getItem(position)as Neuron
                    neuron.filePath=filePath
                    onCheckBoxStateChanged?.invoke(position, true,neuron,currentColor.color)

                }, onFailure = {errorMsg->
                    showToast(errorMsg)
                })

            }else{
//                showToast("取消选中")
                onCheckBoxStateChanged?.invoke(position, false,getItem(position) as Neuron,currentColor.color)

            }
        }
        view.findViewById<TextView>(R.id.tvName).text = item.name
        view.findViewById<TextView>(R.id.tvSampleid).text = item.sampleid
        view.findViewById<TextView>(R.id.tvRegion).text= item.region.toString()

        view.findViewById<View>(R.id.colorNeuron).background.setColorFilter(
            CustomPorterDuffColorFilter(
                Color.argb(255,item.color.x.toInt(),item.color.y.toInt(),item.color.z.toInt()),
                PorterDuff.Mode.SRC_IN
            ))
        return view

    }

    override fun getCount(): Int {
        return neurons.size
    }
    override fun getItem(position: Int): Any? {
        return neurons[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }
    private fun showToast(message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }
}